package com.sky.service.user.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.controller.user.WxPayController;
import com.sky.dto.OrdersDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.user.HistoryOrdersMapper;
import com.sky.mapper.user.OrderDetailMapper;
import com.sky.mapper.user.ShoppingCartMapper;
import com.sky.pojo.OrderDetail;
import com.sky.pojo.Orders;
import com.sky.pojo.ShoppingCart;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.user.HistoryOrdersService;
import com.wechat.pay.java.service.refund.model.CreateRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class HistoryOrdersServiceImpl implements HistoryOrdersService {

    @Autowired
    private HistoryOrdersMapper historyOrdersMapper;
    @Autowired
    private WxPayController wxPayController;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Override
    public Result<PageResult> selectHistoryOrdersList(OrdersPageQueryDTO ordersdTO) {
        ordersdTO.setUserId(BaseContext.getCurrentId());
        PageHelper.startPage(ordersdTO.getPage(),ordersdTO.getPageSize());
        List<Orders> list = historyOrdersMapper.selectHistoryOrders(ordersdTO);
        for (Orders orders : list) {
           List<OrderDetail> details =  historyOrdersMapper.selectOrderDetail(orders.getId());
           orders.setOrderDetailList(details);
        }
        PageInfo<Orders> info = new PageInfo<>(list);
        PageResult result = new PageResult(info.getTotal(),list);
        return Result.success(result);
    }

    @Override
    public Result<PageResult> selectCanCancelOrdeList(OrdersPageQueryDTO ordersdTO) {
        ordersdTO.setUserId(BaseContext.getCurrentId());
        PageHelper.startPage(ordersdTO.getPage(),ordersdTO.getPageSize());
        List<Orders> list = historyOrdersMapper.selectCanCancelOrde(ordersdTO);
        for (Orders orders : list) {
            List<OrderDetail> details =  historyOrdersMapper.selectOrderDetail(orders.getId());
            orders.setOrderDetailList(details);
        }
        PageInfo<Orders> info = new PageInfo<>(list);
        PageResult result = new PageResult(info.getTotal(),list);
        return Result.success(result);
    }

    @Override
    public Result<Orders> getOrdersInfor(Long orderId) {
        Orders order = historyOrdersMapper.selectOrderInfor(orderId);
        List<OrderDetail> details =  historyOrdersMapper.selectOrderDetail(orderId);
        order.setOrderDetailList(details);
        return Result.success(order);
    }

    @Override
    public Result<String> cancleOrder(Long orderId) {
        Orders orders = historyOrdersMapper.selectOrderInfor(orderId);
        Integer status = historyOrdersMapper.selectOrderInfor(orderId).getStatus();
        // 校验订单是否存在
        if (status == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (status > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        orders.setId(orderId);

        // 订单处于待接单状态下取消，需要进行退款
        if (status.equals(Orders.TO_BE_CONFIRMED)) {
            CreateRequest createRequest = new CreateRequest();
            //调用微信支付退款接口
            wxPayController.refund(createRequest);
            createRequest.setOutTradeNo(orders.getNumber());
            createRequest.setOutRefundNo(orders.getNumber());
            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }

        // 更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED_ORDER);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        historyOrdersMapper.cancleOrder(orders);

        return Result.success("取消成功");
    }

    @Override
    public void orderAgain(Long id) {
        // 查询当前用户id
        Long userId = BaseContext.getCurrentId();
        // 根据订单id查询当前订单详情
        List<OrderDetail> orderDetailList = historyOrdersMapper.selectOrderDetail(id);

        // 将订单详情对象转换为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();

            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());

        // 将购物车对象批量添加到数据库
        shoppingCartMapper.insertBatch(shoppingCartList);

    }
}
